﻿using System;
using System.Linq;
using System.Net;

public class BingRestService
{
    public void GetErrorAsync(Action<string> callback)
    {
        var url = "http://api.bing.net/json.aspx?AppId=test&Query=wp7&Sources=web&Sources=image";

        var request = HttpWebRequest.Create(url);
        request.BeginGetResponse(result => callback(EndRequest(result)), request);
    }

    private string EndRequest(IAsyncResult result)
    {
        var request = result.AsyncState as HttpWebRequest;
        var response = request.EndGetResponse(result);

        ErrorResult output;
        using (var stream = response.GetResponseStream())
        {

            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(ErrorResult));
            output = serializer.ReadObject(stream) as ErrorResult;
        }

        return output.SearchResponse.Errors.First().Message;
    }
}

public class ErrorResult
{
    //{"SearchResponse":
    //    {
    //        "Version":"2.2",
    //        "Query":{"SearchTerms":"wp7"},
    //        "Errors":[
    //        {
    //                "Code":1002,
    //                "Message":"Parameter has invalid value.",
    //                "Parameter":"SearchRequest.AppId",
    //                "Value":"test",
    //                "HelpUrl":"http:\/\/msdn.microsoft.com\/en-us\/library\/dd251042.aspx"
    //        }]
    //    }}

    public SearchResponse SearchResponse { get; set; }
}
public class SearchResponse
{
    public string Version { get; set; }
    public Error[] Errors { get; set; }
}
public class Error
{
    public int Code { get; set; }
    public string Message { get; set; }
    public string Parameter { get; set; }
    public string Value { get; set; }
    public string HelpUrl { get; set; }
}
